<?php
$action = "";
if (array_key_exists("action",$_POST)){
    $action = $_POST['action'];
}
$LOGIN_OK = "LOGIN_OK";//login is ok, sending/saving map
$BADLOGIN = "BADLOGIN";//login is bad
$ERROR403 = "ERROR403";//login is ok, but access denied
$ERROR404 = "ERROR404";//no such map

if ($action=="save"){
	$username = $_POST['username'];
	$password = $_POST['password'];
	$data = $_POST['data'];
	$map = $_POST['map'];
    $f = fopen("../data/maplist","r");
    $maps = explode("\n",fread($f,filesize("../data/maplist")));
	fclose($f);
    $foundMap = False;
    for($i=0;$i<count($maps);$i++){
        if ($maps[$i]===$map){
            $foundMap = True;
        }
    }
    if (!$foundMap){
		echo $ERROR404;
	}
	else if ($username=='manux' and $password=="tintin"){
		$path = "../data/maps/".$map;
		//Read version number and add 1
		$f = fopen($path,"r");
		$version = (int)fread($f,filesize($path))+1;
		fclose($f);
		//create new file and new version file
		$newversion = str_pad($version."",4,"0",STR_PAD_LEFT);
		
		$f = fopen($path.".".$newversion,'w');
		fwrite($f,$data);
		fclose($f);
		$f = fopen($path,'w');
		fwrite($f,$newversion);
		fclose($f);
		echo $LOGIN_OK;
		echo "File saved!";
	}
	else{
		echo $BADLOGIN;
	}
}
else if ($action=="open"){
	$username = $_POST['username'];
	$password = $_POST['password'];
	$map = $_POST['map'];
    $f = fopen("../data/maplist","r");
    $maps = explode("\n",fread($f,filesize("../data/maplist")));
	fclose($f);
    $foundMap = False;
    for($i=0;$i<count($maps);$i++){
        if ($maps[$i]===$map){
            $foundMap = True;
        }
    }
    if (!$foundMap){
		echo $ERROR404;
	}
	if ($username=='manux' and $password=="tintin"){
		$path = "../data/maps/".$map;
		//Read version number
		$f = fopen($path,"r");
		$version = (int)fread($f,filesize($path));
		fclose($f);
		//read right version file
		$version = str_pad($version."",4,"0",STR_PAD_LEFT);
		$path = $path.".".$version;
		$f = fopen($path,'r');
		echo $LOGIN_OK;
		echo fread($f,filesize($path));
		fclose($f);
	}
	else{
		echo $BADLOGIN;
	}
}
else{
    ?>
    <h1>Oops!...</h1>
    You probably stumbled upon this page by error... If this happens again please report the problem so we can send our jedi masters to fix the faulty code!
    <?
}
?>

